package chapter17;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.util.HashMap;
public class VeryBigCache {
	private static VeryBigCache cache;
	private HashMap<String,VeryBigRef> cacheMap=new HashMap<String,VeryBigRef>();
	private ReferenceQueue<VeryBig> qa=new ReferenceQueue<VeryBig>();	
	private class VeryBigRef extends SoftReference<VeryBig>
	{
		private String _refId;

		public VeryBigRef(VeryBig referent, ReferenceQueue<? super VeryBig> q) {
			super(referent, q);
			_refId=referent.getId();
			// TODO Auto-generated constructor stub
		}
		public String get_refId() {
			return _refId;
		}
	}			
	public synchronized VeryBigCache getInstance()
	{
		if(cache==null)cache=new VeryBigCache();
		return cache;
	}
	public void addRef(VeryBig vb)
	{
		cleanCache();
		VeryBigRef ref=new VeryBigRef(vb, qa);
		cacheMap.put(vb.getId(), ref);
	}	
	public VeryBig getRef(String id)
	{
		VeryBig vb=null;
		if(cacheMap.containsKey(id))
		{
			VeryBigRef ca=(VeryBigRef)cacheMap.get(id);
			vb=ca.get();
		}
		if(vb==null)
		{
			vb=new VeryBig(id);
			addRef(vb);
		}
		return vb;
	}	
	public void cleanCache()
	{
		VeryBigRef ref=null;
		while((ref=(VeryBigRef)qa.poll())!=null)
		{
			cacheMap.remove(ref.get_refId());
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
